import React, { useEffect, useState } from "react";
import { PropsInterface } from "@/components/ShowBooks/comp/types";
import { BookInfo } from "@/types";
import { checkMajorNameNullOrUndefined, fixLongText } from "@/utils";
import { searchBooksByInfo } from "@/apis";
import { ConfigProvider, Table } from "antd";
import { RenderEmpty } from "@/components/comp/RenderEmpty";
import { Link } from "react-router-dom";

const { Column } = Table;

const TextbookPage: React.FC<PropsInterface> = (props: PropsInterface) => {
  const [booksInfo, setBooksInfo] = useState<BookInfo[]>([]);
  /**
   * check info and reset
   */
  useEffect(() => {
    if (checkMajorNameNullOrUndefined(props.majorName)) {
      searchBooksByInfo("major", props.majorName as string).then((res) => {
        setBooksInfo(res.data);
      });
    } else {
      return;
    }
  }, [props.majorName]);

  useEffect(() => {
    setBooksInfo(props.bookInfoList);
  }, [props.bookInfoList]);
  return (
    <>
      <ConfigProvider renderEmpty={RenderEmpty}>
        <Table dataSource={booksInfo}>
          <Column
            title="课程名称"
            dataIndex="name"
            key="name"
            sorter={(a: BookInfo, b: BookInfo) => {
              return a.name.localeCompare(b.name);
            }}
          ></Column>
          <Column
            title="课程开设学院"
            dataIndex="institute"
            key="institute"
            sorter={(a: BookInfo, b: BookInfo) => {
              return a.institute.localeCompare(b.institute);
            }}
          ></Column>
          <Column
            title="适用专业"
            dataIndex="major"
            key="major"
            render={(text) => {
              return fixLongText(text);
            }}
            sorter={(a: BookInfo, b: BookInfo) => {
              return a.major.localeCompare(b.major);
            }}
          ></Column>
          <Column
            title="课程性质"
            dataIndex="characteristics"
            key="characteristics"
            sorter={(a: BookInfo, b: BookInfo) => {
              return a.characteristics.localeCompare(b.characteristics);
            }}
          ></Column>
          <Column
            title="先修课程"
            dataIndex="prerequisite"
            key="prerequisite"
          ></Column>
          <Column
            title="参考书目"
            dataIndex="reference"
            key="reference"
          ></Column>
          <Column
            title="操作"
            dataIndex="id"
            key="id"
            render={(text) => {
              return (
                <>
                  <Link target="_blank" to={`/book/${text}`}>
                    详情
                  </Link>
                </>
              );
            }}
          ></Column>
        </Table>
      </ConfigProvider>
    </>
  );
};

export default TextbookPage;
